package yxy.cherry.chat;

import java.net.InetSocketAddress;

import yxy.apple.http.server.HttpServer;
import yxy.apple.http.server.business.RequestDispatcher;
import yxy.apple.http.server.converter.ConverterImpl;
import yxy.apple.logger.Logger;
import yxy.apple.nio.client.Client;
import yxy.banana.launcher.Reactable;
import yxy.banana.socket.receiver.Observer;
import yxy.cherry.chat.client.ClientBundler;
import yxy.cherry.chat.client.ClientInitializer;
import yxy.cherry.game.base.message.MessageStation;

public final class Reactor implements Reactable<Configuration> {
	protected static Logger logger = Logger.create(Reactor.class);

	public static final Reactor instance = new Reactor();

	private HttpServer server = null;
	private ClientBundler bundler = null;
	private MessageStation station = new MessageStation();

	private Reactor() {

	}

	public void shutdown() {
		if (this.server != null) {
			logger.info("正在关闭HTTP服务...");
			this.server.stop();
		}
		if (this.station != null) {
			logger.info("正在关闭Message Station...");
			this.station.close();
		}
		if (this.bundler != null) {
			logger.info("正在关闭与路由中心间的内部连接...");
			this.bundler.stop();
		}
		{
			logger.info("正在清理等待回应的事务请求...");
			Observer.shared.clear();
		}
	}

	public void start(Configuration configuration) throws Exception {
		{
			logger.info("正在初始化Message Station...");
			this.station.open(configuration.MessageStationThreads);
		}
		{
			logger.info("正在初始化到路由中心的内部连接簇...");
			Client client = new Client(new ClientInitializer(),
					new InetSocketAddress(configuration.InternalClient.RouteCenterIP, configuration.InternalClient.RouteCenterPort),
					configuration.InternalClient.Threads);
			this.bundler = new ClientBundler(client, configuration.InternalClient.PatrolInterval);
			this.bundler().start(configuration.InternalClient.Channels);
		}

	}

	public void http(Configuration configuration) throws Exception {
		{
			logger.info("正在加载接口...");
			RequestDispatcher.getInstance().initAdapter(configuration.URLpackageName);
			RequestDispatcher.getInstance().setConverter(new ConverterImpl(configuration.Converters));
		}
		{
			logger.info("正在初始化HTTP服务");
			HttpServerInitializer initializer = new HttpServerInitializer();
			this.server = new HttpServer(configuration.HTTPServer.Port, configuration.HTTPServer.Threads, initializer.provideSslContext());
			this.server.start();
		}
	}

	public ClientBundler bundler() {
		return this.bundler;
	}

	public MessageStation station() {
		return this.station;
	}
}
